package com.jsecode.net.common;

import org.slf4j.Logger;

import com.jsecode.lib.util.ByteUtil;
import com.jsecode.lib.util.LoggerUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;

public class NetUtil {
    private static Logger logger = LoggerUtil.getLogNetSend();

    public static ChannelFuture writeAndFlush(Channel channel, Object msg)  {
        if (channel != null && channel.isActive()) {
            ChannelFuture future = channel.writeAndFlush(msg);
            logSend(channel, msg);
            return future;
        }
        return null;
    }
    
    private static void logSend(Channel channel, Object msg) {
        if (logger.isDebugEnabled()) {
            if (msg instanceof byte[]) {
                logger.debug("socket: {}  {} ", channel.remoteAddress(), ByteUtil.formatHexStr((byte[])msg));
            } else if (msg instanceof ByteBuf) {
                logger.debug("socket: {}  {} ", channel.remoteAddress(), ByteBufUtil.hexDump((ByteBuf)msg));
                
            } else {
                logger.debug("socket: {}  {} ", channel.remoteAddress(), msg);
            }
        }
    }

}
